package com.probox.modules.controller.centre;

import cn.hutool.core.date.DateUtil;
import com.probox.common.core.enums.CmsType;
import com.probox.common.core.enums.DataStatus;
import com.probox.common.core.utils.DateUtils;
import com.probox.common.core.utils.SecurityUtils;
import com.probox.common.core.utils.StringUtils;
import com.probox.common.core.utils.money.MoneyUtils;
import com.probox.common.core.web.domain.AjaxResult;
import com.probox.common.entity.domain.platfom.PlatformInfo;
import com.probox.common.entity.domain.platfom.PlatformStoreTarget;
import com.probox.common.entity.service.centre.ICustomerInfoService;
import com.probox.common.entity.service.centre.IOrderInfoService;
import com.probox.common.entity.service.centre.IProductCountService;
import com.probox.common.entity.service.customer.ICustomerCollectService;
import com.probox.common.entity.service.customer.ICustomerFundDetailService;
import com.probox.common.entity.service.customer.ICustomerFundService;
import com.probox.common.entity.service.job.IOrderPayInfoService;
import com.probox.common.entity.service.order.IOrderInfoItemService;
import com.probox.common.entity.service.platfom.IPlatformCmsService;
import com.probox.common.entity.service.platfom.IPlatformInfoService;
import com.probox.common.entity.service.platfom.IPlatformStoreTargetService;
import com.probox.common.entity.service.system.ISysUserService;
import com.probox.common.entity.vo.centre.HomeVo;
import com.probox.common.entity.vo.centre.WarningDataVo;
import com.probox.common.entity.vo.centre.customer.CustomerQueryVo;
import com.probox.common.entity.vo.centre.order.HomeQueryVo;
import com.probox.common.entity.vo.centre.order.OrderDataVo;
import com.probox.common.entity.vo.centre.order.OrderQueryVo;
import com.probox.order.api.domain.OrderQuery;
import com.probox.platform.api.domain.PlatformApiCmsVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;

/**
 * @author Kite
 * @date 2021/7/23
 */
@Api(value = "首页数据模块", tags = {"首页数据接口"})
@RestController
@RequestMapping("/centre-data/count/home")
public class CentreHomeController {

    @Autowired
    private IOrderInfoService orderInfoService;

    @Autowired
    private ICustomerInfoService customerInfoService;

    @Autowired
    public IProductCountService productCountService;

    @Autowired
    private IPlatformInfoService platformInfoService;

    @Autowired
    private IPlatformCmsService platformCmsService;

    @Autowired
    private IPlatformStoreTargetService storeTargetService;

    @Autowired
    private IOrderPayInfoService orderPayInfoService;

    @Autowired
    private ICustomerFundDetailService customerFundDetailService;

    @Autowired
    private ICustomerFundService customerFundService;

    @Autowired
    private IOrderInfoItemService orderInfoItemService;

    @Autowired
    private ICustomerCollectService customerCollectService;


    /**
     * 查询首页数据
     *
     * @return
     */
    @ApiOperation(value = "查询首页数据")
    @ApiResponses({@ApiResponse(code = 200, message = "OK", response = HomeVo.class)})
    @GetMapping("getHomeData")
    public AjaxResult getHomeData(HomeQueryVo queryVo) throws Exception {
        HomeVo homeVo = new HomeVo();

        OrderQuery query = new OrderQuery();
        if (StringUtils.isNotEmpty(queryVo.getStartTime())) {
            query.setStartDate(queryVo.getStartTime());
            query.setEndDate(queryVo.getEndTime()+" 23:59:59");
        }else{
            query.setStartDate(DateUtils.formateToday(new Date()));
            query.setEndDate(query.getStartDate()+" 23:59:59");
        }
        query.setOrderType("vip");
        Long vip = orderPayInfoService.countAmount(query);
        if (vip == null) vip = 0L;
        homeVo.setVipAmount(MoneyUtils.changeF2Y(vip));

        query.setOrderType("scan");
        Long scan = orderPayInfoService.countAmount(query);
        if (scan == null) scan = 0L;
        homeVo.setScanAmount(MoneyUtils.changeF2Y(scan));

        query.setOrderType("admin");
        Long good = orderPayInfoService.countAmount(query);
        if (good == null) good = 0L;
        homeVo.setAdminGoodAmount(MoneyUtils.changeF2Y(good));

        homeVo.setTotalMoney(MoneyUtils.changeF2Y(vip+scan+good));

        query.setFundStatus("0");
        Long jifen = customerFundDetailService.countJiFen(query);
        if (jifen == null) jifen = 0l;
        homeVo.setJifen(jifen);
        query.setFundStatus("1");

        Long useJifen = customerFundDetailService.countJiFen(query);
        if (useJifen == null) useJifen = 0l;
        homeVo.setUseJifen(useJifen);

        homeVo.setTotalJifen(customerFundService.countJiFen(query));

        query.setOrderType("good");
        homeVo.setDownload(orderInfoItemService.countAmount(query));
        query.setOrderType("maiduan");
        homeVo.setMaiduan(orderInfoItemService.countAmount(query));

        homeVo.setCollect(customerCollectService.countAmount(query));

        PlatformInfo byId = platformInfoService.getById(SecurityUtils.getPlatformId());
        homeVo.setPlatformName(byId.getPlatformName());
        String isAuth = byId.getIsAuth();
        if (DataStatus.valid.getKey().equals(isAuth) & DateUtil.nextMonth().after(byId.getAuthTime())) {
            isAuth = "2";
        }
        homeVo.setPlatformState(isAuth);
        homeVo.setExpireDate(byId.getAuthTime());

        homeVo.setRegisters(customerInfoService.selectCustomerTotal(query).longValue());
        //总会员数据
        query.setStartDate(null);
        query.setEndDate(null);
        homeVo.setMemberCount(customerInfoService.selectCustomerTotal(query));

        return AjaxResult.success(homeVo);
    }


    /**
     * 查询门店月度目标
     *
     * @return
     */
    @ApiOperation(value = "查询门店月度目标")
    @ApiResponses({@ApiResponse(code = 200, message = "OK", response = HomeVo.class)})
    @GetMapping("getMonthTargetData")
    public AjaxResult getMonthTargetData(HomeQueryVo queryVo) throws Exception {
        HomeVo homeVo = new HomeVo();
        OrderQueryVo orderQueryVo = new OrderQueryVo();
        if (StringUtils.isNotEmpty(queryVo.getStoreId())){
            String[] stores = queryVo.getStoreId().split(",");
            List<Long> list = new ArrayList<>();
            for(String s:stores){
                list.add(Long.parseLong(s));
            }
            orderQueryVo.setStoreList(list);
        }else{
            Long storeId = SecurityUtils.getStoreId();
            if (storeId != null){
                List<Long> list = new ArrayList<>();
                list.add(storeId);
                orderQueryVo.setStoreList(list);
            }
        }

        //目标
        PlatformStoreTarget target = storeTargetService.sumQueryList(orderQueryVo);

        Map<String,Object> rst = new HashMap<>();

        rst.put("moneyRate",0);
        //服务人数
        rst.put("manCount",0);
        rst.put("manCountRate",0);

        //服务项目数
        rst.put("serviceCount",0);
        rst.put("serviceCountRate",0);
        //耗卡金额
        rst.put("haoka",0);
        rst.put("haokaRate",0);

        //月度目标
        rst.put("target",target);
        //完成金额
        rst.put("money",0);
        if (target != null) {
            //完成现金
            BigDecimal payAmount = orderInfoService.sumPayAmount(orderQueryVo);
            rst.put("money",payAmount);

            Calendar calendar = Calendar.getInstance(Locale.CHINA); // 创建一个Calendar对象
            int year = calendar.get(Calendar.YEAR); // 获取年份
            int month = calendar.get(Calendar.MONTH); // 获取月份（注意：月份从0开始计数）
            calendar.set(year, month, 1); //
            calendar.set(Calendar.HOUR,0);
            calendar.set(Calendar.MINUTE,0);
            calendar.set(Calendar.SECOND,0);

            month +=1;
            if (month == 2 && isLeapYear(year)) { // 如果是闰年并且是二月，则设置为29号作为最后一天
                calendar.set(Calendar.DAY_OF_MONTH, 29);
            } else {
                calendar.set(Calendar.DAY_OF_MONTH, getLastDayOfMonth(calendar)); // 否则根据月份计算最后一天
            }

            rst.put("moneyRate", new BigDecimal((payAmount.longValue() * 10000.0) / (target.getMoney().longValue() * 100)).setScale(2, RoundingMode.FLOOR));
            //服务人数
            rst.put("manCount",0);
            rst.put("manCountRate", 0);

            //服务项目数
            rst.put("serviceCount", 0);
            rst.put("serviceCountRate",0);

        }else{
            target = new PlatformStoreTarget();
            target.setMoney(0L);
            target.setHaokaMoney(0L);
            target.setHaokaPepole(0L);
            target.setHaokaItem(0L);
            rst.put("target",target);
        }
        return AjaxResult.success(rst);
    }

    private static boolean isLeapYear(int year) {
        return ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)); // 判断是否是闰年
    }

    private static int getLastDayOfMonth(Calendar calendar) {
        calendar.add(Calendar.MONTH, 1); // 将日期调到下个月第一天
        calendar.add(Calendar.DATE, -1); // 再次向前移动一天得到上个月最后一天
        return calendar.get(Calendar.DAY_OF_MONTH); // 返回最后一天的日期
    }

    /**
     * 查询首页数据
     *
     * @return
     */
    @ApiOperation(value = "查询公告列表")
    @ApiResponses({@ApiResponse(code = 200, message = "OK", response = PlatformApiCmsVo.class)})
    @GetMapping("getAnnouncementList/{pageNum}")
    public AjaxResult getAnnouncementList(@PathVariable("pageNum") Long pageNum) {
        return AjaxResult.success(platformCmsService.getCms(pageNum, CmsType.notice.getKey()));
    }


    /**
     * 提供（相对）精确的除法运算。当发生除不尽的情况时，由scale参数指
     * 定精度，以后的数字四舍五入
     *
     * @param v1    被除数
     * @param v2    除数
     * @param scale 表示需要精确到小数点以后几位
     * @return 两个参数的商
     */
    public static String div(String v1, String v2, int scale) {
        if (scale < 0) {
            throw new IllegalArgumentException("The scale must be a positive integer or zero");
        }
        BigDecimal b1 = new BigDecimal(v1);
        BigDecimal b2 = new BigDecimal(v2);
        return b1.divide(b2, scale, BigDecimal.ROUND_HALF_UP).toString();
    }

}
